#include <iostream>
#include <string>
#include <vector>
#include <sqlite3.h>

class SqliteHelper {
    public:
        typedef int(*SqliteCallback)(void*,int,char**,char**);//语句返回结果
        SqliteHelper(const std::string &dbfile) : _dbfile(dbfile), _handler(nullptr){}
        
        bool open(int safe_leve = SQLITE_OPEN_FULLMUTEX/*串行化，安全等级*/) {
            //int sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs );

            int ret = sqlite3_open_v2(_dbfile.c_str()/*文件名*/, &_handler,/*句柄地址*/ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | safe_leve,/*打开方式*/ nullptr);
            if (ret != SQLITE_OK) {
                std::cout << "创建/打开sqlite数据库失败: ";
                std::cout << sqlite3_errmsg(_handler)/*获取错误信息*/ << std::endl;
                return false;
            }
            return true;
        }
        //arg：指定路径
        bool exec(const std::string &sql, SqliteCallback cb, void *arg) {
            //int sqlite3_exec(sqlite3*, char *sql, int (*callback)(void*,int,char**,char**), void* arg, char **err)
            int ret = sqlite3_exec(_handler, sql.c_str(), cb/*用于处理 语句的结果集*/, arg, nullptr);
            if (ret != SQLITE_OK) {
                std::cout << sql << std::endl;
                std::cout << "执行语句失败: ";
                std::cout << sqlite3_errmsg(_handler) << std::endl;
                return false;
            }
            return true;
        }
        void close() {
            //int sqlite3_close_v2(sqlite3*);
            if (_handler) sqlite3_close_v2(_handler);
        }
    private:
        std::string _dbfile;
        sqlite3 *_handler;//操作句柄，SQLite 数据库连接的 sqlite3 对象的指针
};